package org.lee.cr;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * NumResource
 *
 * @author dralee
 * @date 2022-03-09 13:40:08
 **/
@Slf4j
public class NumResource {
    private static int num = 0;
    private static ReadWriteLock lock = new ReentrantReadWriteLock(); // 默认非公平锁
    private static Lock writeLock = lock.writeLock();
    private static Lock readLock = lock.readLock();

    public void read() {
        readLock.lock();
        try {
            log.info("current num: {}", num);
        } finally {
            readLock.unlock();
        }
    }

    public void set(Integer num) {
        writeLock.lock();
        try {
            log.info("{}===>{}", Thread.currentThread().getName(), num);
            NumResource.num = num;
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            log.error("{}", e);
        } finally {
            writeLock.unlock();
        }
    }
}
